﻿/*  ------------------------------------------------------------------------
	 NQ Common Services Library
	 
	 Homepage: http://www.awzhome.de/
	 ------------------------------------------------------------------------
	 
	 The contents of this file are subject to the Mozilla Public License
	 Version 1.1 (the "License"); you may not use this file except in
	 compliance with the License. You may obtain a copy of the License at
	 http://www.mozilla.org/MPL/
	 
	 Software distributed under the License is distributed on an "AS IS"
	 basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
	 License for the specific language governing rights and limitations
	 under the License.
	
	 The Original Code is code of NQ Common Services Library.

	 The Initial Developer of the Original Code is Andreas Weizel.
	 Portions created by the Initial Developer are
	 Copyright (C) 2006-2009 Andreas Weizel. All Rights Reserved.
	 
	 Contributor(s): (none)
	 
	 Alternatively, the contents of this file may be used under the terms
	 of the GNU General Public License Version 2.0 or later (the "GPL"),
	 or the GNU Lesser General Public License Version 2.1 or later (the
	 "LGPL"), in which case the provisions of the GPL or the LGPL are
	 applicable instead of those above. If you wish to allow use of your
	 version of this file only under the terms of the GPL or the LGPL and
	 not to allow others to use your version of this file under the MPL,
	 indicate your decision by deleting the provisions above and replace
	 them with the notice and other provisions required by the GPL or the
	 LGPL. If you do not delete the provisions above, a recipient may use
	 your version of this file under the terms of any of the MPL, the GPL
	 or the LGPL.
	 ------------------------------------------------------------------------
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AWZhome.NQ.Core;
using AWZhome.NQ.Core.Fluent;
using AWZhome.NQ.CommonServices.Visual;
using System.Windows;
using System.Collections.ObjectModel;

namespace AWZhome.NQ.CommonServices
{
	[NQExportedService(Category = NQHostMode.GUI)]
	public class UpdateSelectView : ViewServiceBase, Services.IUpdateSelectViewService
	{
		private UpdateSelectViewVisual _viewVisual;
		private ObservableCollection<ReleaseListEntry> _installedReleaseList = new ObservableCollection<ReleaseListEntry>();
		private ObservableCollection<ReleaseListEntry> _uninstalledReleaseList = new ObservableCollection<ReleaseListEntry>();
		private IUpdateManager _servUpdate;
		private IResourceManager _servRes;
		private IPersistManager _servPersist;

		public UpdateSelectView(ISession sessionService)
			: base(sessionService)
		{
		}

		#region UpdateSelectView methods and properties

		public WizardDialogService WizardDialogService
		{
			get
			{
				return this.ViewManager as WizardDialogService;
			}
		}

		public ObservableCollection<ReleaseListEntry> InstalledReleaseList
		{
			get
			{
				return _installedReleaseList;
			}
			set
			{
				_installedReleaseList = value;
			}
		}

		public ObservableCollection<ReleaseListEntry> UninstalledReleaseList
		{
			get
			{
				return _uninstalledReleaseList;
			}
			set
			{
				_uninstalledReleaseList = value;
			}
		}

		#endregion

		#region NQViewServiceBase methods and properties

		protected override bool CheckSessionType(ISession session)
		{
			return true;
		}

		public override string DisplayName
		{
			get
			{
				return String.Empty;
			}
		}

		public override bool IsChanged
		{
			get
			{
				return false;
			}
		}

		public override bool CanBeClosed
		{
			get
			{
				return false;
			}
		}

		public override bool IsLoggable
		{
			get
			{
				return false;
			}
		}

		public override bool IsDocument
		{
			get
			{
				return false;
			}
		}

		public override object DisplayedObject
		{
			get
			{
				return _viewVisual;
			}
		}

		public override System.Windows.Media.ImageSource Icon
		{
			get
			{
				return null;
			}
		}

		public override ViewDisplayMode DockingType
		{
			get
			{
				return ViewDisplayMode.InClientArea;
			}
		}

		public override void Initialize(string context)
		{
			base.Initialize(context);

			// Initialize visual view
			_viewVisual = new UpdateSelectViewVisual();
			_viewVisual.DataContext = this;

			// Get service instances
			_servRes = ServiceCore
				.Get<Services.IResourceService>()
				.To;
			_servUpdate = ServiceCore
				.Get<Services.IUpdateService>()
				.To;
			_servPersist = ServiceCore
				.Get<Services.IPersistService>()
				.To;

			// Set event handlers
			_servUpdate.UpdateProgress += _servUpdate_UpdateProgress;
			_viewVisual.checkShowBetas.Click += new RoutedEventHandler(checkShowBetas_Click);
		}

		public override void LoadContents()
		{
			base.LoadContents();

			// Load settings
			ConfigData showBetas = _servPersist.GetSetting("NQCS", "updateShowBetas", true);
			if (showBetas != null)
			{
				_viewVisual.checkShowBetas.IsChecked = showBetas.AsBoolean();
			}

			// Fill the update lists, if possible
			if (_servUpdate.UpdateInformationLoaded)
			{
				this.FillUpdateLists();
			}
		}

		public override void SaveContents(ViewSaveReason saveReason)
		{
			base.SaveContents(saveReason);

			// Save the settings
			_servPersist.SetSetting("NQCS", "updateShowBetas",
				new ConfigData().FromBoolean(_viewVisual.checkShowBetas.IsChecked.Value), true);
		}

		#endregion

		#region Other private methods

		private void checkShowBetas_Click(object sender, RoutedEventArgs e)
		{
			// We should reload the release lists to show/hide the experimental releases
			if (_servUpdate.UpdateInformationLoaded)
			{
				this.FillUpdateLists();
			}
		}

		/// <summary>
		/// Marks a component in the visible component list for installation.
		/// </summary>
		/// <param name="relEntry">Release list entry.</param>
		internal void MarkComponentForInstall(ReleaseListEntry relEntry)
		{
			if (relEntry != null)
			{
				// Add the release to installation job list
				if (!relEntry.IsUpToDate && !_servUpdate.JobList.Contains(relEntry.Release))
				{
					try
					{
						_servUpdate.JobList.Add(relEntry.Release);
					}
					catch (UpdateCompatibilityException ex)
					{
						UpdateCompatibilityWarnWindow warnWindow = new UpdateCompatibilityWarnWindow(relEntry,
							ex);
						warnWindow.ShowDialog();
					}
				}

				// Update the item
				this.UpdateListEntry(relEntry);
			}
		}

		/// <summary>
		/// Marks a component in the visible component list for uninstall.
		/// </summary>
		/// <param name="relEntry">Release list entry.</param>
		internal void MarkComponentForUninstall(ReleaseListEntry relEntry)
		{

		}

		private void _servUpdate_UpdateProgress(object sender, UpdateProgressEventArgs e)
		{
			if (e.ProgressType == UpdateProgressEventType.Ready)
			{
				this.FillUpdateLists();
			}
		}

		private void FillUpdateLists()
		{
			_installedReleaseList.Clear();
			_uninstalledReleaseList.Clear();

			// Create list entries
			foreach (IProduct product in _servUpdate.Products)
			{
				foreach (IRelease release in product.Releases)
				{
					if (_viewVisual.checkShowBetas.IsChecked.Value || !release.IsExperimental)
					{
						ReleaseListEntry updateEntry = new ReleaseListEntry();
						updateEntry.Release = release;
						UpdateListEntry(updateEntry);

						// Put the entry into appropriate list
						if (NQServiceManager.Instance.GetComponentInfo(product.Name) != null)
						{
							// Component is already installed and active
							_installedReleaseList.Add(updateEntry);
						}
						else
						{
							// Component is not installed
							_uninstalledReleaseList.Add(updateEntry);
						}
					}
				}
			}

			_viewVisual.DataContext = this;
		}

		private void UpdateListEntry(ReleaseListEntry listEntry)
		{
			IRelease release = listEntry.Release;
			IProduct product = (from p in _servUpdate.Products
										 where p.Name == release.ProductName
										 select p).SingleOrDefault();

			listEntry.Title = release.ProductName + " " + release.DisplayVersion;
			listEntry.Description = release.Description.Trim();
			listEntry.ReleaseTimeStamp = release.Date.ToShortDateString() + " " + release.Date.ToShortTimeString();
			listEntry.IsRecommended = release.IsRecommended;
			listEntry.IsExperimental = release.IsExperimental;
			listEntry.IsInstallable = _servUpdate.CheckInstallConditions(release.Conditions, true).IsInstallable;
			listEntry.IsSelectedForInstall = _servUpdate.JobList.Contains(release);
			listEntry.IsUpToDate = false;

			// Set the status text
			INQComponentInfo compInfo = NQServiceManager.Instance.GetComponentInfo(product.Name);
			if (compInfo != null)
			{
				if (release.Version > compInfo.Version)
				{
					// Available component is newer than the installed
					listEntry.StatusText = _servRes.GetResString("NQCS", "UpdateDialog.ListEntry.Updated");
				}
				else if (release.Version < compInfo.Version)
				{
					// Available component is older than the installed
					listEntry.StatusText = _servRes.GetResString("NQCS", "UpdateDialog.ListEntry.Older");
				}
				else
				{
					// Available component is the same as installed
					listEntry.StatusText = _servRes.GetResString("NQCS", "UpdateDialog.ListEntry.UpToDate");
					listEntry.IsUpToDate = true;
				}

				// Recommendations are only senseful for updates
				if (listEntry.IsRecommended)
				{
					listEntry.StatusText = _servRes.GetResString("NQCS", "UpdateDialog.ListEntry.Recommended");
				}
			}

			if (listEntry.IsExperimental)
			{
				// Available release is experimental
				listEntry.StatusText = _servRes.GetResString("NQCS", "UpdateDialog.ListEntry.Experimental");
			}
			if (listEntry.IsSelectedForInstall)
			{
				// Available component is already selected for installation
				listEntry.StatusText = _servRes.GetResString("NQCS", "UpdateDialog.ListEntry.Selected");
			}
		}

		private string FormatCondition(IUpdateCondition condition)
		{
			string result = condition.Name;
			switch (condition.VersionCondition)
			{
				case NQCondition.Equal:
					result += " ";
					break;
				case NQCondition.Greater:
					result += " > ";
					break;
				case NQCondition.Lower:
					result += " < ";
					break;
				case NQCondition.Greater | NQCondition.Equal:
					result += " >= ";
					break;
				case NQCondition.Lower | NQCondition.Equal:
					result += " <= ";
					break;
				case NQCondition.Lower | NQCondition.Greater:
					result += " <> ";
					break;
				default:
					result += " ";
					break;
			}
			result += condition.Version.ToString();

			return result;
		}

		#endregion
	}
}
